<template>
	<view class="agent-list">
		<button @click="showAddAgentModal">添加代理</button>
		<!-- 添加 uni-table 开始标签 -->
		 <!-- id，代理人名称，联系方式，代理片区，创建时间，修改时间，操作生成二维码或查看二维码 -->
		<uni-table>
			<uni-tr>
				<uni-th>代理ID</uni-th>
				<uni-th>代理人账号</uni-th>
				<uni-th>代理人名称</uni-th>
				<uni-th>联系方式</uni-th>
				<uni-th>操作</uni-th>
			</uni-tr>
			<uni-tr v-for="agent in agents" :key="agent.id">
				<uni-td>{{ agent.id }}</uni-td>
				<uni-td>{{ agent.loginName }}</uni-td>
				<uni-td>{{ agent.userName }}</uni-td>
				<uni-td>{{ agent.phone }}</uni-td>
				<uni-td>
					<button size="mini" @click="generateQRCode(agent)" v-show="agent.isCode==0">生成二维码</button>
					<button size="mini" @click="getQRCode(agent.id)" v-show="agent.isCode==1">查看二维码</button>
					<button size="mini" @click="showEditModal(agent)">修改</button>
					<button size="mini" @click="deleteAgent(agent.id)">删除</button>
				</uni-td>
			</uni-tr>
		</uni-table>
		<!-- 分页组件 -->
		<uni-pagination :total="total" :current="page" :page-size="pageSize" @change="handlePageChange" />
		<!-- 添加代理弹窗 -->
		<uni-popup ref="agentModal">
			<view class="modal-content">
				<uni-forms ref="agentForm" :model="newAgent">
					<uni-forms-item name="id" v-show="false">
						<uni-easyinput v-model="newAgent.id" placeholder="用户名id" />
					</uni-forms-item>
					<uni-forms-item name="userName">
						<uni-easyinput v-model="newAgent.userName" placeholder="请输入用户名" />
					</uni-forms-item>
					<uni-forms-item name="loginName" v-if="type === 'add'">
						<uni-easyinput v-model="newAgent.loginName" placeholder="请输入账号" />
					</uni-forms-item>
					<uni-forms-item name="password">
						<uni-easyinput type="password" v-model="newAgent.password" placeholder="请输入密码" />
					</uni-forms-item>
					<uni-forms-item name="phone">
						<uni-easyinput v-model="newAgent.phone" placeholder="请输入手机号码" />
					</uni-forms-item>
					<button type="primary" @click="submitAgentForm">提交</button>
				</uni-forms>
			</view>
		</uni-popup>
		<uni-popup ref="imgModal">
			<image v-if="base64" :src="base64" mode="aspectFit"></image>
		</uni-popup>
	</view>
</template>

<script>
import { adminRedirectionMixin } from '@/common/commonMixins.js';
import { getAgentsApi, updateUserApi, addUserApi, deleteUserApi, generateCodeApi, getCodeApi } from '@/api';
export default {
	mixins: [adminRedirectionMixin],
		data() {
			return {
				agents: [],
				type: "add",
				total: 0,
				page: 1,
				pageSize: 4,
				base64:'',
				newAgent: {
					id: null,
					userName: '',
					password: '123456asd',
					phone: '',
					role: 1
				}
			};
		},
		mounted() {
			this.fetchAgents();
		},
		methods: {
			//查询代理列表
			async fetchAgents ({loading = true} = {}) {
				if (loading) {
					uni.showLoading({
						title: 'loading',
						mask: true
					});
				}
				try {
					const res = await getAgentsApi({
						currentPage: this.page,
          	pageSize: 10
					})
					this.agents = res.data.records
					this.total = res.data.total
				} finally {
					if (loading) {
						uni.hideLoading()
					}
				}
				
				
				// console.log(res)
				// await uni.request({
				// 	url: `${this.$config.API_BASE_URL}/`,
				// 	method: 'GET',
				// 	data: {
				// 		currentPage: this.page
				// 	},
				// 	success: (res) => {
				// 		if (res.data.code == 200) {
				// 			this.agents = res.data.data.records
				// 			this.total = res.data.data.total
				// 		} else {
				// 			uni.showToast({
				// 				title: res.data.message,
				// 				icon: 'none'
				// 			});
				// 		}
				// 	}
				// });
			},
			// 显示新增代理模态框
			showAddAgentModal() {
				this.newAgent = {
					id: null,
					userName: '',
					password: '123456asd',
					phone: '',
					role: 1
				};
				this.$refs.agentModal.open();
			},
			// 显示编辑代理模态框
			showEditModal(agent) {
				this.newAgent = {
					...agent,
					role: 1
				};
				this.$refs.agentModal.open();
			},
			//校验信息
			Regex(result) {
				const flag = false;
				// 账号正则：只能包含字母、数字，长度为 3 - 20 位
				const usernameRegex = /^[a-zA-Z0-9]{3,20}$/;
				// 手机号码正则：11 位数字，以 1 开头
				const phoneRegex = /^1[3-9]\d{9}$/;
				// 密码正则：长度为 6 - 20 位，至少包含一个字母和一个数字
				const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/;
				if (!result.userName) {
					uni.showToast({
						title: '请输入账号',
						icon: 'none'
					});

				}
				// else if (!usernameRegex.test(result.userName)) {
				// 	uni.showToast({
				// 		title: '账号格式错误，只能包含字母和数字，长度为 3 - 20 位',
				// 		icon: 'none'
				// 	});
				// }
				else if (!result.phone) {
					uni.showToast({
						title: '请输入手机号码',
						icon: 'none'
					});
				} else if (!phoneRegex.test(result.phone)) {
					uni.showToast({
						title: '手机号码格式错误，请输入 11 位有效手机号码',
						icon: 'none'
					});
				} else if (!result.password) {
					uni.showToast({
						title: '请输入密码',
						icon: 'none'
					});
				}
				// else if (!passwordRegex.test(result.password)) {
				// 	uni.showToast({
				// 		title: '密码格式错误，长度为 6 - 20 位，至少包含一个字母和一个数字',
				// 		icon: 'none'
				// 	});
				// }
				else {
					return true;
				}
				return flag;
			},
           //提交订单
			async submitAgentForm() {
				try {
					
					const result = await this.$refs.agentForm.validate();
					
					// 使用 this.Regex 调用方法
					if (this.Regex(result)) {
						uni.showLoading({
							title: 'loading',
							mask: true
						});
						if (result.id) {
							console.log("修改的代理信息:", this.newAgent)
							const { data } = await updateUserApi(this.newAgent)
							// 成功添加后刷新列表
							this.fetchAgents();
							uni.showToast({
								title: data == 1 ? '修改代理成功' : '修改代理失败',
								icon: data == 1 ? 'success' : 'error'
							});
					
						} else {
							console.log("新增代理信息:", this.newAgent)

							const { data } = await addUserApi(this.newAgent)
							// 成功添加后刷新列表
							this.fetchAgents();
							uni.showToast({
								title: data == 1 ? '添加代理成功' : '添加代理失败',
								icon: data == 1 ? 'success' : 'error'
							});
						}
					}

				} catch (e) {
					uni.showToast({
						title: e.message,
						icon: 'none'
					});

				} finally {
					uni.hideLoading();
					this.$refs.agentModal.close();
				}
			},
			//获取二维码
			async generateQRCode(agent) {
				try {
					uni.showLoading({
						title: 'loading',
						mask: true
					});
					const {data} = await generateCodeApi(agent)
					const base64Data = data.qrCodeContent;

					// 在获取到 base64Data 后，检查是否有前缀，若无则添加
					this.base64 = `data:image/png;base64,${base64Data}`;
					console.log(this.base64)
					this.$refs.imgModal.open();
					// this.fetchAgents({loading: false});
					const target = this.agents.find(item => item.id == agent.id)
					target.isCode = 1

				} catch (error) {
					console.error('二维码生成请求失败:', error);
					uni.showToast({
						title: '网络请求失败，请稍后重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading()
				}
			},
			//删除代理
			async deleteAgent (agentId) {
				const {data} = await deleteUserApi({
					userId: agentId
				})
				// 成功添加后刷新列表
				this.fetchAgents();
				uni.showToast({
					title: data == 1 ? '删除代理成功' : '删除代理失败',
					icon: data == 1 ? 'success' : 'error'
				});
			
			},
			// 处理分页变化
			handlePageChange(newPage) {
				this.page = newPage.current;
				// 这里添加处理分页变化的逻辑，例如向后端发送请求获取新数据
				this.fetchAgents();
				console.log('切换到第', newPage, '页');
			},
			//获取二维码
			async getQRCode (agentId) {
				try {

					uni.showLoading({
						title: 'loading',
						mask: true
					});
					const {data} = await getCodeApi({
						userId: agentId
					})
	
					const base64Data = data;
					// 在获取到 base64Data 后，检查是否有前缀，若无则添加
					this.base64 = `data:image/png;base64,${base64Data}`;
					console.log(this.base64)
					this.$refs.imgModal.open();
					// this.fetchAgents();
				} finally {
					uni.hideLoading()
				}
				 
			}
		}
	};
</script>

<style scoped>
	.agent-list {
		padding: 20px;
	}

	.modal-content {
		padding: 20px;
	}
</style>